import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { HMI_TIME_SETTING_API } from "@/api/hmi/time-setting.api";
import type {
  TimeSettingInfo,
  TimeSettingUpdateRequest,
  TimeSettingUpdateResponse,
  TimeSettingFormData,
} from "@/api/hmi/time-setting.api";

/**
 * 时间设置 Store
 */
export const useTimeSettingStore = defineStore("timeSetting", () => {
  // 响应式状态
  const currentTimeSetting = ref<TimeSettingInfo | null>(null);
  const isLoading = ref<boolean>(false);
  const isUpdating = ref<boolean>(false);
  const isReady = ref<boolean>(false);
  const lastUpdateResult = ref<TimeSettingUpdateResponse | null>(null);

  /**
   * 设置当前时间设置信息
   * @param timeSetting 时间设置信息
   */
  const setCurrentTimeSetting = (timeSetting: TimeSettingInfo) => {
    currentTimeSetting.value = timeSetting;
    isReady.value = true;
  };

  /**
   * 重置时间设置状态
   */
  const resetTimeSettingState = () => {
    currentTimeSetting.value = null;
    isReady.value = false;
    lastUpdateResult.value = null;
  };

  /**
   * 获取当前时间设置信息
   * @returns 当前时间设置信息或默认值
   */
  const getCurrentTimeSetting = (): TimeSettingFormData => {
    if (currentTimeSetting.value) {
      return {
        zone: currentTimeSetting.value.Zone,
        year: currentTimeSetting.value.Year,
        month: currentTimeSetting.value.Month,
        day: currentTimeSetting.value.Day,
        hour: currentTimeSetting.value.Hour,
        minute: currentTimeSetting.value.Minute,
        sec: currentTimeSetting.value.Sec,
      };
    }

    // 返回默认时间设置
    const now = new Date();
    return {
      zone: 8, // 时间设置所在定值区的编号
      year: now.getFullYear(),
      month: now.getMonth() + 1,
      day: now.getDate(),
      hour: now.getHours(),
      minute: now.getMinutes(),
      sec: now.getSeconds(),
    };
  };

  /**
   * 查询时间设置
   * @param cpu CPU 编号
   * @returns Promise<TimeSettingInfo[]>
   */
  const fetchTimeSetting = (cpu: number) => {
    return new Promise<TimeSettingInfo[]>((resolve, reject) => {
      isLoading.value = true;

      HMI_TIME_SETTING_API.fetchTimeSetting(cpu)
        .then((res) => {
          if (res && res.length > 0) {
            setCurrentTimeSetting(res[0]);
          }
          resolve(res);
        })
        .catch((error) => {
          console.error("fetchTimeSetting error:", error);
          reject(error);
        })
        .finally(() => {
          isLoading.value = false;
        });
    });
  };

  /**
   * 更新时间设置
   * @param cpu CPU 编号
   * @param timeSettingData 时间设置数据
   * @returns Promise<TimeSettingUpdateResponse>
   */
  const updateTimeSetting = (cpu: number, timeSettingData: TimeSettingFormData) => {
    return new Promise<TimeSettingUpdateResponse>((resolve, reject) => {
      isUpdating.value = true;

      const updateRequest: TimeSettingUpdateRequest[] = [
        {
          zone: timeSettingData.zone,
          year: timeSettingData.year,
          month: timeSettingData.month,
          day: timeSettingData.day,
          hour: timeSettingData.hour,
          minute: timeSettingData.minute,
          sec: timeSettingData.sec,
        },
      ];

      HMI_TIME_SETTING_API.updateTimeSetting(cpu, updateRequest)
        .then((res) => {
          lastUpdateResult.value = res;

          // 更新成功后，更新本地状态
          if ("status" in res && res.status === "success") {
            const updatedTimeSetting: TimeSettingInfo = {
              Zone: timeSettingData.zone,
              Year: timeSettingData.year,
              Month: timeSettingData.month,
              Day: timeSettingData.day,
              Hour: timeSettingData.hour,
              Minute: timeSettingData.minute,
              Sec: timeSettingData.sec,
            };
            setCurrentTimeSetting(updatedTimeSetting);
          }

          resolve(res);
        })
        .catch((error) => {
          console.error("updateTimeSetting error:", error);
          lastUpdateResult.value = {
            error: error.message || "更新失败",
            message: error.message || "时间设置更新失败",
            code: error.code || -1,
          };
          reject(error);
        })
        .finally(() => {
          isUpdating.value = false;
        });
    });
  };

  /**
   * 重置更新结果
   */
  const resetUpdateResult = () => {
    lastUpdateResult.value = null;
  };

  /**
   * 验证时间设置数据
   * @param timeSettingData 时间设置数据
   * @returns 验证结果
   */
  const validateTimeSetting = (
    timeSettingData: TimeSettingFormData
  ): {
    isValid: boolean;
    errors: string[];
  } => {
    const errors: string[] = [];

    // 验证时区
    if (timeSettingData.zone < -12 || timeSettingData.zone > 12) {
      errors.push("时区必须在-12到12之间");
    }

    // 验证年份
    if (timeSettingData.year < 2000 || timeSettingData.year > 2099) {
      errors.push("年份必须在2000到2099之间");
    }

    // 验证月份
    if (timeSettingData.month < 1 || timeSettingData.month > 12) {
      errors.push("月份必须在1到12之间");
    }

    // 验证日期
    if (timeSettingData.day < 1 || timeSettingData.day > 31) {
      errors.push("日期必须在1到31之间");
    }

    // 验证小时
    if (timeSettingData.hour < 0 || timeSettingData.hour > 23) {
      errors.push("小时必须在0到23之间");
    }

    // 验证分钟
    if (timeSettingData.minute < 0 || timeSettingData.minute > 59) {
      errors.push("分钟必须在0到59之间");
    }

    // 验证秒
    if (timeSettingData.sec < 0 || timeSettingData.sec > 59) {
      errors.push("秒必须在0到59之间");
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  };

  return {
    // 状态
    currentTimeSetting,
    isLoading,
    isUpdating,
    isReady,
    lastUpdateResult,

    // 方法
    setCurrentTimeSetting,
    resetTimeSettingState,
    getCurrentTimeSetting,
    fetchTimeSetting,
    updateTimeSetting,
    resetUpdateResult,
    validateTimeSetting,
  };
});

/**
 * 在 setup 外使用
 */
export function useTimeSettingStoreWithOut() {
  return useTimeSettingStore(store);
}
